﻿<template>
  <div id="app">
    <div v-show="isLoading" class="loadingBox"></div>
    <router-view />
  </div>
</template>

<script>
import XLSX from "xlsx";

let audio = "";

export default {
  name: "App",
  data() {
    return {
//      baseIp: "http://10.18.3.14:8913",
      baseIp: "http://127.0.0.1:8913",
      // baseIp: "61.183.71.118:2180",
      // baseIp: "http://192.168.43.253:8080",
      loading: null,
      isLoading: false,
      isRequest: true,
    };
  },
  computed: {},
  watch: {},
  methods: {
    //根据所选的IP和端口号注册打印服务
    demoSetClodopJS: function (strSrc) {
      var that = this;
      strSrc = "http://" + "localhost:8000" + "/CLodopfuncs.js?priority=1";
      var oscript = that.demoCreateCLodopJSscript(strSrc);
    },
    //远程打印
    //  01     02
    userSetClodopJS: function (strSrc) {
      var that = this;
      strSrc = "http://" + strSrc + "/CLodopfuncs.js?priority=1";
      var oscript = that.demoCreateCLodopJSscript(strSrc);
    },
    demoCreateCLodopJSscript: function (strSrc) {
      var ScriptSS = document.getElementsByTagName("script");
      for (var i in ScriptSS) {
        if (ScriptSS[i].src && ScriptSS[i].src.indexOf("CLodopfuncs.js") >= 0) {
          if (ScriptSS[i].parentNode)
            ScriptSS[i].parentNode.removeChild(ScriptSS[i]);
        }
      }
      var oscript = document.createElement("script");
      if (strSrc.indexOf("src=") >= 0) {
        strSrc = strSrc.match(/=[\',\"][^\',^\"].*(?=[\',\"])/i);
        strSrc = strSrc[0].slice(2);
      }
      oscript.src = strSrc;
      var head =
        document.head ||
        document.getElementsByTagName("head")[0] ||
        document.documentElement;
      head.insertBefore(oscript, head.firstChild);
      return oscript;
    },
  },
  created() {
    let that = this;
    that.demoSetClodopJS();
    localStorage.setItem("baseIpPort", that.baseIp);

    window.IOT = {
      userSetClodopJS(strSrc) {
        that.userSetClodopJS(strSrc);
      },
      upLoadFile(url, param, success) {
        let token = localStorage.getItem("token");

        let baseUrl = that.baseIp + "/wms";

        localStorage.setItem("baseUrl", baseUrl);
        $.ajax({
          //jQuery方法，此处可以换成其它请求方式
          url: baseUrl + url,
          dataType: "json",
          type: "post",
          data: param,
          headers: {
            Accept: "*/*",
            "access-token": token,
          },
          processData: false, //不去处理发送的数据
          contentType: false, //不去设置Content-Type请求头
          error: function (res) {
            IOT.tips(
              err.statusText === "timeout" ? "请求超时!" : err || "未知的错误!",
              "error",
              1000,
              () => {
                IOT.hideOverlay();
              }
            );
            console.error(err.statusText, err || "未知的错误!");
          },
          success: function (res) {
            success(res);
          },
        });
      },
      getServerData(url, type, param, success, noToRet, isAsync) {
        let params = {};
        let token = localStorage.getItem("token");
        let baseUrl = that.baseIp + "/wms";
        localStorage.setItem("baseUrl", baseUrl);
        type === "get"
          ? (params = PF.JSON(param))
          : (params = JSON.stringify(param));
        let async = true;

        PF.isNull(isAsync) ? (async = isAsync) : (async = true);
        // console.log(
        //     "token:",
        //     token,
        //     " url:",
        //     url,
        //     " params:",
        //     JSON.stringify(params)
        // );
        $.ajax({
          type: type,
          dataType: "json",
          timeout: 1000 * 60 * 60,
          data: params,
          headers: {
            Accept: "application/json; charset=utf-8",

            "access-token": token,
          },
          contentType: "application/json",
          url: baseUrl + url,
          async: async,
          success: (res, textStatus, request) => {
            if (res.code === 10006 || res.code === 10007) {
              IOT.tips("访问令牌参数失效,请重新登录!", "error", 1000, () => {
                that.$router.push({ name: "login" });
              });
              return false;
            }
            if (noToRet) {
              success(res);
            } else {
              success(PF.toRet(res, true));
            }
          },
          complete: function( xhr,data ){
            // 获取相关Http Response header
            // var wpoInfo = {
            //     // 服务器端时间
            //     "date" : xhr.getResponseHeader('Date'),
            //     // 如果开启了gzip，会返回这个东西
            //     "contentEncoding" : xhr.getResponseHeader('Content-Encoding'),
            //     // keep-alive ？ close？
            //     "connection" : xhr.getResponseHeader('Connection'),
            //     // 响应长度
            //     "contentLength" : xhr.getResponseHeader('Content-Length'),
            //     // 服务器类型，apache？lighttpd？
            //     "server" : xhr.getResponseHeader('Server'),
            //     "vary" : xhr.getResponseHeader('Vary'),
            //     "transferEncoding" : xhr.getResponseHeader('Transfer-Encoding'),
            //     // text/html ? text/xml?
            //     "contentType" : xhr.getResponseHeader('Content-Type'),
            //     "cacheControl" : xhr.getResponseHeader('Cache-Control'),
            //     // 生命周期？
            //     "exprires" : xhr.getResponseHeader('Exprires'),
            //     "lastModified" : xhr.getResponseHeader('Last-Modified'),
            //     "access-token": xhr.getResponseHeader('access-token')
            // };
            // 在这里，做想做的事。。。
            var refreshToken = xhr.getResponseHeader('access-token');
            if(refreshToken){
              let token = localStorage.setItem("token", refreshToken);
            }
        },
          error: (err) => {
            IOT.tips(
              err.statusText === "timeout" ? "请求超时!" : err || "未知的错误!",
              "error",
              1000,
              () => {
                IOT.hideOverlay();
              }
            );
            console.error(err.statusText, err || "未知的错误!");
          },
        });
      },
      getServerData1(url, type, param, success, noToRet) {
        let params = JSON.parse(JSON.stringify(param));
        // console.log(localStorage.getItem("token"));

        if (type === "get") {
          that.$http
            .get(url, { params: params })
            .then((res) => {
              if (noToRet) {
                success(res.data);
              } else {
                success(PF.toRet(res));
              }
            })
            .catch((err) => {
              console.error(err || "未知的错误!", "error");
            });
        } else if (type === "post") {
          that.$http
            .post(url, params)
            .then((res) => {
              if (noToRet) {
                success(res.data);
              } else {
                success(PF.toRet(res));
              }
            })
            .catch((err) => {
              console.error(err || "未知的错误!", "error");
            });
        } else if (type === "put") {
          that.$http
            .put(url, params)
            .then((res) => {
              if (noToRet) {
                success(res.data);
              } else {
                success(PF.toRet(res));
              }
            })
            .catch((err) => {
              console.error(err || "未知的错误!", "error");
            });
        }
      },
      showOverlay(content) {
        let text = "";
        if (content) {
          text = content;
        }
        that.loading = that.$loading({
          lock: true,
          text: text || "",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
      },
      hideOverlay() {
        if (that.loading) {
          that.loading.close();
        }
      },
      tips(message, type, time, end) {
        let duration = 1500;
        if (time) {
          duration = time;
        }

        that.$message({
          showClose: true,
          dangerouslyUseHTMLString: true,
          message: message,
          type: type,
          duration: duration,
          onClose: end,
        });
      },
    };

    window.PF = {
      audioPlay(mp3Name) {
        audio = "/mp3/" + mp3Name + ".mp3";
        audio = new Audio(audio);
        //监听循环播放
        $(audio).bind("ended", function () {
          audio.play();
        });
        audio.play(); //播放 mp3这个音频对象
      },
      audioStop() {
        audio.pause();
      },
      calcTime(start, end) {
        if (PF.isNull(start) && PF.isNull(end)) {
          let a = new Date(start);
          let b = new Date(end);
          let c = Math.floor(((b - a) / 1000 / 60 / 60) * 10000) / 10000;
          return c;
        } else {
          return " - ";
        }
      },
      readExcel(e, callback) {
        //表格导入
        const files = e.target.files;
        // console.log(files);
        if (files.length <= 0) {
          //如果没有文件名
          return false;
        } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
          IOT.tips("上传格式不正确，请上传xls或者xlsx格式！", "error");
          return false;
        }

        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: "binary",
            });
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            // console.log(ws);
            callback(ws);
            // this.$refs.upload.value = '';
          } catch (e) {
            return false;
          }
        };
        fileReader.readAsBinaryString(files[0]);
      },
      subtraction(x, y) {
        // 小数点减法
        let n = 10000000000;
        let z = (x * n - y * n) / n;
        return z;
      },
      codeProcess(code) {
        let data = "";
        for (let key in code) {
          if (key !== "code") {
            if (data !== "") {
              data += "&";
            }
            if (PF.isNull(code[key])) {
              data += key + ":" + code[key];
            } else {
              data += key + ":" + null;
            }
          }
        }
        return data;
      },
      codeToObj(data) {
        let arr = data.split("&");
        let obj = {};
        for (let i = 0; i < arr.length; i++) {
          let q = arr[i].split(":");
          if (q[1] === "null") {
            obj[q[0]] = null;
          } else {
            obj[q[0]] = q[1];
          }
        }
        return obj;
      },
      changePToChangeQ(data) {
        // 改变单位改变数量
        let detail = PF.JSON(data);
        let oldTransRatio = 0; // 改变前的系数
        let nowTransRatio = 0; // 改变后的系数
        for (let i = 0; i < detail.packDetails.length; i++) {
          if (detail.packDetailId === detail.oldP) {
            // 改变后的单位id 等于 改变前的单位id (单位未改变)
            nowTransRatio = oldTransRatio = 1;
          } else if (
            detail.packDetails[i].packDetailId1 === detail.packDetailId
          ) {
            // (单位改变了) 找到改变后的单位
            nowTransRatio = detail.packDetails[i].transRatio1; // 拿到系数
          } else if (detail.packDetails[i].packDetailId1 === detail.oldP) {
            // (单位改变了) 找到改变前的单位
            oldTransRatio = detail.packDetails[i].transRatio1; // 拿到系数
          }
        }
        let quantity = (detail.oldQ * oldTransRatio) / nowTransRatio;
        return quantity;
      },
      CPCQ(data, qArr) {
        let detail = PF.JSON(data);

        for (let i = 0; i < qArr.length; i++) {
          let quantity = detail[qArr[i]];
          for (let j = 0; j < detail.packDetails.length; j++) {}
        }
      },
      /**
       * data: 加字段时使用
       */
      getSysParamUdfData(memo, data, callback) {
        // 自定义字段
        IOT.getServerData(
          "/sys/params/findByMemo",
          "get",
          { memo: memo },
          (ret) => {
            if (ret.code === 200) {
              let udfs = ret.rows;
              let arr = PF.JSON(data);
              // 为data赋key
              for (let i = 0; i < data.length; i++) {
                for (let j = 0; j < udfs.length; j++) {
                  arr[i][udfs[j].paramCode] = "";
                }
              }
              callback(arr, udfs);
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
        );
      },
      getDataDictUdfData(dataDictCode, callback) {
        // 数据字典自定义
        IOT.getServerData(
          "/data/dict/details/findBydDataDictCode",
          "get",
          { dataDictCode: dataDictCode },
          (ret) => {
            if (ret.code === 200) {
              let rows = ret.rows;
              callback(rows);
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
        );
      },
      getOrganizations(callback) {
        IOT.getServerData("/organizations/list", "get", {}, (ret) => {
          if (ret.code === 200) {
            let rows = ret.rows;
            callback(rows);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
      getSuppliers(callback) {
        IOT.getServerData("/supplier/manages/allList", "get", {}, (ret) => {
          if (ret.code === 200) {
            let rows = ret.rows;
            callback(rows);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
      getCustomers(callback) {
        IOT.getServerData("/customers/allList", "get", {}, (ret) => {
          if (ret.code === 200) {
            let rows = ret.rows;
            callback(rows);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
      getCarriers(callback) {
        IOT.getServerData("/carriers/allList", "get", {}, (ret) => {
          if (ret.code === 200) {
            let rows = ret.rows;
            callback(rows);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
      getWares(callback) {
        IOT.getServerData("/ware/infos/list", "get", {}, (ret) => {
          if (ret.code === 200) {
            let rows = ret.rows;
            callback(rows);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
      getPackDetails(packCode, callback) {
        IOT.getServerData(
          "/pack/details/list",
          "get",
          { packCode: packCode },
          (ret) => {
            if (ret.code === 200) {
              let rows = ret.rows;
              callback(rows);
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
        );
      },
      getNowFormatDate() {
        let date = new Date();
        let seperator1 = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        let currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
      },
      setLocal(key, val) {
        if (typeof val === "object") {
          localStorage.setItem(key, JSON.stringify(val));
        } else {
          localStorage.setItem(key, val);
        }
      },
      getLocal(key, type) {
        let value = localStorage.getItem(key);
        if (!PF.isNull(value)) {
          return value;
        } else if (type && type === "json") {
          return JSON.parse(value);
        } else if (type && type === "number") {
          return Number(value);
        } else {
          return value;
        }
      },
      removeLocal(key) {
        localStorage.removeItem(key);
      },
      getModule(path) {
        if (path.length <= 1) {
          return false;
        }
        path += "/";
        let isHave = false;
        let moduleName = "";
        for (let i = 0; i < path.length; i++) {
          if (path[i] === "/") {
            if (!isHave) {
              isHave = true;
            } else {
              return moduleName;
            }
          } else {
            moduleName += path[i];
          }
        }
      },
      isNull(val, type) {
        if (type === "") {
          if (val === null || val === undefined) {
            return false;
          } else {
            return true;
          }
        } else {
          if (val === "" || val === null || val === undefined) {
            return false;
          } else {
            return true;
          }
        }
      },
      toRet(res, isAjax) {
        let ret = {};
        let data = {};
        if (isAjax) {
          data = res;
        } else {
          data = res.data;
        }

        if (PF.isNull(data.code, "")) {
          ret.code = data.code;
        }
        if (PF.isNull(data.message, "")) {
          ret.message = data.message;
        }
        if (PF.isNull(data.data, "") && typeof data.data === "object") {
          if (data.data.length === undefined) {
            if (PF.isNull(data.data.pageNum, "")) {
              ret.pageNumber = data.data.pageNum;
            }
            if (PF.isNull(data.data.pageSize, "")) {
              ret.pageSize = data.data.pageSize;
            }
            if (PF.isNull(data.data.pages, "")) {
              ret.pages = data.data.pages;
            }
            if (PF.isNull(data.data.total, "")) {
              ret.total = data.data.total;
            }
            if (PF.isNull(data.data.list, "")) {
              ret.rows = data.data.list;
            }
          } else if (data.data.length >= 0) {
            if (PF.isNull(data.data, "")) {
              ret.rows = data.data;
            }
          }
        }
        return ret;
      },
      getServerData: (url, type, queryQaram, loading, success2) => {
        queryQaram = JSON.stringify(queryQaram);
        var res = "";
        let token = localStorage.getItem("token");
        // console.log(token);
        let baseIp = "localhost:8080";
        // let baseIp = "101.34.10.18:8080";
        let baseUrl = "http://" + baseIp + "/wms";
        if (loading) {
          if (type == "post") {
            $.ajax({
              type: type,
              dataType: "json",
              timeout: 30000,
              data: queryQaram,
              headers: {
                Accept: "*/*",
                "access-token": token,
              },
              contentType: "application/json",
              url: baseUrl + url,
              async: false,
              beforeSend: () => {
                PF.publicLoadingShow(loading);
              },
              success: (data) => {
                PF.publicLoadingHide();
                success2(data);
              },
              error: () => {
                PF.publicLoadingHide();
                alert("请求失败,联系管理员!");
              },
            });
          } else if (type == "get") {
            var param = "?";
            queryQaram = queryQaram.replace(/"/g, "");
            queryQaram = queryQaram.replace(/{/g, "");
            queryQaram = queryQaram.replace(/}/g, "");
            queryQaram = queryQaram.replace(/:/g, "=");
            queryQaram = queryQaram.replace(/,/g, "&");
            url = url + "?" + queryQaram;
            $.ajax({
              type: type,
              dataType: "json",
              timeout: 30000,

              headers: {
                Accept: "*/*",
                "access-token": token,
              },
              contentType: "application/json",
              url: baseUrl + url,
              async: false,
              beforeSend: () => {
                PF.publicLoadingShow(loading);
              },
              success: (data) => {
                PF.publicLoadingHide();
                res = data;
              },
              error: () => {
                PF.publicLoadingHide();
                alert("请求失败,联系管理员!");
              },
            });
          }
        } else {
          if (type == "post") {
            $.ajax({
              type: type,
              dataType: "json",
              timeout: 30000,
              data: queryQaram,
              headers: {
                Accept: "*/*",
                "access-token": token,
              },
              contentType: "application/json",
              url: baseUrl + url,
              async: false,
              success: (data) => {
                PF.publicLoadingHide();
                res = data;
              },
              error: () => {
                PF.publicLoadingHide();
                alert("请求失败,联系管理员!");
              },
            });
          } else if (type == "get") {
            var param = "?";
            queryQaram = queryQaram.replace(/"/g, "");
            queryQaram = queryQaram.replace(/{/g, "");
            queryQaram = queryQaram.replace(/}/g, "");
            queryQaram = queryQaram.replace(/:/g, "=");
            queryQaram = queryQaram.replace(/,/g, "&");
            url = url + "?" + queryQaram;
            $.ajax({
              type: type,
              dataType: "json",
              timeout: 30000,

              headers: {
                Accept: "*/*",
                "access-token": token,
              },
              contentType: "application/json",
              url: baseUrl + url,
              async: false,
              success: (data) => {
                PF.publicLoadingHide();
                res = data;
              },
              error: () => {
                PF.publicLoadingHide();
                alert("请求失败,联系管理员!");
              },
            });
          }
        }
        return res;
      },
      validator: (
        rule,
        value,
        callback,
        tableName,
        fieldName,
        fieldValue,
        type,
        idValue
      ) => {
        let form = {
          tableName: tableName, // 表名
          fieldName: fieldName, // 字段名
          fieldValue: fieldValue, // 字段值
          type: type, // 0-新增 1-更新
          idValue: idValue, // type为0时不传，type为1是必传，id值
        };

        IOT.getServerData("/validator", "post", form, (ret) => {
          if (
            ret.code === 100001 ||
            ret.code === 100002 ||
            ret.code === 100004
          ) {
            callback(new Error(ret.message || "已重复"));
          } else if (ret.code === 100003) {
            callback();
          } else {
            PF.publicMessage(
              ret.message || "服务器请求失败，稍后再试！",
              "error"
            );
            callback();
          }
        });

        /*that.$http.post('/validator', form).then(res=>{
      if(res.data.code === 100001 || res.data.code === 100002 || res.data.code === 100004){
          callback(new Error(data.message || '已重复'));
      } else if (res.data.code === 100003) {
          callback();
      }else{
          PF.publicMessage(res.data.message || '服务器请求失败，稍后再试！', 'error');
          callback();
      }
  }).catch(err=>{
      console.error(err || '未知的错误!','error');
  });*/
      },
      validatorNew: (rule, value, callback, fieldName, wareId) => {
        let form = {
          [fieldName]: value, // 字段名
          wareId,
        };
        IOT.getServerData("/area/infos/validator", "post", form, (ret) => {
          if (
            ret.code === 100001 ||
            ret.code === 100002 ||
            ret.code === 100004
          ) {
            callback(new Error(ret.message || "已重复"));
          } else if (ret.code === 100003) {
            callback();
          } else {
            PF.publicMessage(
              ret.message || "服务器请求失败，稍后再试！",
              "error"
            );
            callback();
          }
        });
      },
      JSON: (data) => {
        if (typeof data === "object") {
          return JSON.parse(JSON.stringify(data));
        } else if (typeof data === "string") {
          return JSON.parse(data);
        }
      },
      toTree: (list = [], disabled = false) => {
        const data = JSON.parse(JSON.stringify(list)); // 浅拷贝不改变源数据
        let result = [];
        if (!Array.isArray(data)) {
          return result;
        }
        data.forEach((item) => {
          delete item.children;
        });
        let map = {};
        data.forEach((item) => {
          map[item.id] = item;
          if (disabled) {
            item.disabled = disabled;
          }
        });
        data.forEach((item) => {
          let parent = map[item.parentId];
          if (parent) {
            (parent.children || (parent.children = [])).push(item);
          } else {
            result.push(item);
          }
        });
        return result;
      },
      publicLoadingShow: (content) => {
        // document.querySelector('.loadingBox').style.display = 'block';
        // that.isLoading = true;
        let text = "";
        if (content) {
          text = content;
        }
        that.loading = that.$loading({
          lock: true,
          text: text,
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
          // background: 'rgba(255,255,255,0.9)'
        });
      },
      publicLoadingHide: () => {
        // document.querySelector('.loadingBox').style.display = 'none';
        // that.isLoading = false;
        if (that.loading) {
          that.loading.close();
        }
      },
      publicMessage(message, type, time, end) {
        let duration = 1500;
        if (time) {
          duration = time;
        }

        that.$message({
          showClose: true,
          dangerouslyUseHTMLString: true,
          message: message,
          type: type,
          duration: duration,
          onClose: end,
        });
      },
      /**
       * 将字符串中的占位符转换为给定字符
       * @param str 目标字符串 形如：'/users/{0}?password={1}'，其中0\1代表占位符所对应的参数的顺序
       * @returns {*} 返回一个新的字符串
       */
      format: (str) => {
        if (!str || !str.length) {
          return str;
        }
        for (
          var tempStr = str, i = 0, len = arguments.length - 1;
          i < len;
          i++
        ) {
          tempStr = tempStr.replace(
            new RegExp("\\{" + i + "\\}", "g"),
            arguments[i + 1]
          );
        }
        return tempStr;
      },
      getSysParam(param) {
        IOT.getServerData("/sys/params", "get", param, (ret) => {
          if (ret.code === 200) {
            return ret.rows[0].value;
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        });
      },
    };
  },
};
</script>

<style lang="less">
#app {
  overflow: hidden;
}
</style>
